package com.ruoyi.media.forestApi.common;

import com.alibaba.fastjson.JSON;
import com.dtflys.forest.http.ForestQueryMap;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.ruoyi.media.forestApi.WechatMpApi;
import com.ruoyi.media.forestApi.vo.Tokens;
import com.ruoyi.media.utils.WxUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Component
public class WechatMpApiRequest {


  private final WechatMpApi wechatMpApi;




  /**
   * 获取token参数
   * @param cookieStr
   * @return
   */
  public Tokens queryToken(String cookieStr){
    String cookies = WxUtils.resetCookies(cookieStr); //将数据库的cookies解析为网页可用的参数
    ForestResponse response = wechatMpApi.queryToken(cookies);
    ForestRequest redirectReq  = response.redirectionRequest();
    if(redirectReq != null && redirectReq.getQuery() != null){
      ForestQueryMap map = redirectReq.getQuery();
      return JSON.parseObject(JSON.toJSONString(map),Tokens.class);
    }
    return null;
  }

//
//  /**
//   * 根据公众号名称查询公众号数据
//   * @param nickName
//   * @return
//   */
//  public BizData queryWechatMpByName(String nickName){
//    BizData bizData = new BizData();
//    WechatMpAccount wechatMpAccount = wechatMpAccountService.queryAvailableCookies();
//    List<ForestCookie> forestCookies = WxUtil.resetForestCookie(wechatMpAccount.getCookies());
//    if(forestCookies != null){
//      WechatMpTokenVo wechatMpTokenVo = queryToken(wechatMpAccount.getCookies());
//      if(wechatMpTokenVo != null && XStringUtils.isNotEmpty(wechatMpTokenVo.getToken())){
//        ForestResponse response = wechatMpApi.searchMpByKeyWord(nickName,wechatMpTokenVo.getToken(),(request, cookies) -> {
//          // 将之前调用登入接口获得的Cookie传入请求发送到服务端
//          cookies.addAllCookies(forestCookies);
//        });
//        String res = response.getContent();
//        if(XStringUtils.isNotEmpty(res)){
//          WxResultBody wxResultBody =  WechatUtil.parseWxResultBody(res,new TypeReference<WxResultBody<List<BizData>>>() {});
//          if(wxResultBody.getBase_resp().getRet().equals(0)){
//            if(wxResultBody.getList() != null){
//              List<BizData> dataList = (ArrayList) wxResultBody.getList();
//              dataList.forEach((item)->{
//                if(nickName.equals(item.getNickname())){
//                  bizData.setAlias(item.getAlias());
//                  bizData.setFakeid(item.getFakeid());
//                  bizData.setNickname(item.getNickname());
//                  bizData.setSignature(item.getSignature());
//                  bizData.setRound_head_img(item.getRound_head_img());
//                  bizData.setService_type(item.getService_type());
//                }
//              });
//            }
//          }
//        }
//      }else{
//        wechatMpAccount.setLoginStatus(0);
//        wechatMpAccountService.updateById(wechatMpAccount);
//      }
//    }else{
//      wechatMpAccount.setLoginStatus(0);
//      wechatMpAccountService.updateById(wechatMpAccount);
//    }
//    return bizData;
//  }
//
//
//  /**
//   * 获取极致了数据最新收录文章
//   * @return
//   */
//  public JSONArray queryNewMpJzlData(){
//    return  JSONArray.parseArray(wechatMpApi.queryNewMpJzlData());
//  }
//
//
//  /**
//   * 根据biz参数获取文章链接等数据
//   * @return
//   */
//  public List<Article> searchArticleByBiz(String biz){
//    WechatMpAccount wechatMpAccount = wechatMpAccountService.queryAvailableCookies();
//    List<ForestCookie> forestCookies = WxUtil.resetForestCookie(wechatMpAccount.getCookies());
//    WechatMpTokenVo wechatMpTokenVo = queryToken(wechatMpAccount.getCookies());
//    if(wechatMpTokenVo != null && XStringUtils.isNotEmpty(wechatMpTokenVo.getToken())){
//      String response = wechatMpApi.searchMpArticleByBiz(biz,wechatMpTokenVo.getToken(),(request, cookies) ->{
//        cookies.addAllCookies(forestCookies);
//      });
//      if(XStringUtils.isNotEmpty(response)){
//        if(JSONObject.parseObject(response).getJSONObject("base_resp").getInteger("ret") == 0){
//          WxResultBody wxResultBody =  WechatUtil.parseWxResultBody( response, new TypeReference<WxResultBody<List<Article>>>() {});
//          if(wxResultBody.getApp_msg_list() != null){
//            List<Article> resData = new ArrayList<>();
//            List<Article> articleList =  (ArrayList)wxResultBody.getApp_msg_list();
//            for(Article item:articleList){
//              long yesterday =  Long.parseLong(WxUtil.getYesterday()); //昨天的日期
//              long updateTime = Long.parseLong(WxUtil.timeStampToStr(item.getUpdate_time()).substring(0,8)); //将时间戳转换为时间字符串
//              if(updateTime >= yesterday){
//                resData.add(item);
//              }
//            }
//            return articleList;
//          }
//        }
//      }
//    }else{
//      wechatMpAccount.setLoginStatus(0); //当前cookies失效的情况下直接将账号设置未登录
//      wechatMpAccountService.updateById(wechatMpAccount); //修改账号状态
//    }
//    return null;
//  }
//
//
//  /**
//   * 根据文章链接处理文章内容
//   * @return
//   */
//  public WechatMpOwnerArticleList queryArticleContent(String url){
//    WechatMpOwnerArticleList wechatMpOwnerArticleList = new WechatMpOwnerArticleList();
//    try{
//      String resContent =  wechatMpApi.queryArticleContent(url);
//      if(XStringUtils.isNotEmpty(resContent)){
//        Document doc = Jsoup.parse(resContent);
//        if(XStringUtils.isNotEmpty(resContent)){    //如果有文章内容的情况下
//          if(doc.getElementById("js_mpvedio") != null && resContent.contains("duration_ms")
//                  && resContent.contains("video_quality_wording")){ //说明是视频类型的
//            String videoTitle =  doc.getElementById("js_video_page_title").text();
//            String coverText = resContent.substring(resContent.indexOf("window.__mpVideoCoverUrl"),resContent.indexOf("window.__mpVideoTransInfo"));
//            String coverUrl = coverText.substring(28,coverText.indexOf("';"));
//            String videoText = resContent.substring(resContent.indexOf("duration_ms"),resContent.indexOf("video_quality_wording")); //截取第一个高清视频的代码片段
//            String link =  videoText.substring(videoText.indexOf("url") + 6,videoText.indexOf("',")); //获取视频链接前面的下标
//            String videoUrl = link.replace("\\x26amp;","&");
//            wechatMpOwnerArticleList.setContentType(2); //类型为2代表视频类型
//            wechatMpOwnerArticleList.setVideoUrl(videoUrl);
//            wechatMpOwnerArticleList.setCover(coverUrl);
//            wechatMpOwnerArticleList.setTitle(videoTitle);
//          }  else {
//            //不是视频的链接  应该是图文的 内容不为空并且不是原创
//            if(doc.getElementById("js_content") != null && doc.getElementById("copyright_logo") == null){
//
//              if(resContent.contains("msg_cdn_url")){  //获取封面链接
//                int cdnUrlIndex = resContent.indexOf("msg_cdn_url");
//                String resCdnUrl =  resContent.substring(cdnUrlIndex,cdnUrlIndex + 300); //截取封面代码片段
//                wechatMpOwnerArticleList.setCover(resCdnUrl.substring(resCdnUrl.indexOf("http"),resCdnUrl.indexOf(";") - 1)); //文章封面
//              }
//
//              if(doc.getElementById("activity-name") != null){
//                wechatMpOwnerArticleList.setTitle(doc.getElementById("activity-name").text());
//              }
//
//              if(doc.getElementById("js_name") != null ){
//                wechatMpOwnerArticleList.setMpNickname(doc.getElementById("js_name").text());
//              }
//
//              Elements content = doc.getElementById("js_content").children();
//              List<DictModel> listDict  = sysDictService.getDictItems("wechat_mp_violationkeyword"); //根据字段表获取字段值
//              for (Element element : content) {
//                Elements elChildren =  element.children();
//                for(Element children : elChildren){
//                  listDict.forEach((item)->{
//                    if(item.getTitle().equals("tag")){  //移除所有违规标签
//                      children.select(item.getValue()).remove();
//                    }
//                    if(item.getTitle().equals("strToNull")){  //将违规词替换为空
//                      if(children.text().equals(item.getValue())){
//                        children.remove();
//                      }
//                    }
//                  });
//                  String imageUrl = children.select("img").attr("data-src");  //获取所有图片链接
//                  Elements imgElements = children.select("img");
//                  for(Element imgEl : imgElements){
//                    imgEl.attr("src",imgEl.attr("data-src"));
//                  }
//                  if(XStringUtils.isNotEmpty(imageUrl) && !imageUrl.contains("gif")){
//                    InputStream is = null;
//                    try{
//                      URL urlImage = new URL(imageUrl);
//                      is = urlImage.openStream();
//                      Result re =  QRCodeHelpers.parseImage(is);
//                      if(re != null){
//                        children.select("img").remove();
//                      }
//                    } catch (IOException io){
//                      io.printStackTrace();
//                    } finally {
//                      is.close();
//
//                    }
//                  }
//                }
//              }
//              wechatMpOwnerArticleList.setContentType(1); // 类型为1是图文类型
//              wechatMpOwnerArticleList.setContent(content.toString()); //插入内容
//            }
//          }
//        }
//      }
//    }catch (Exception e){
//      e.printStackTrace();
//    }
//    return wechatMpOwnerArticleList;
//  }
//
//
//
//  /**
//   * 根据开始时间和结束时间获取收益数据
//   * @return
//   */
//  public JSONObject queryBankInfoData(String token,String accountCookies){
//    String  lastDate  = WxUtils.getPastDate(7,new Date()); //获取七天前的时间
//
//    Date currDate = new Date();
//    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//    String currStr = sdf.format(currDate);   //获取的当前时间
//
//    List<ForestCookie> forestCookies = WxUtil.resetForestCookie(accountCookies);
//    Map<String,Object> params = new HashMap<String,Object>(){
//      {
//        put("start_date",lastDate);
//        put("end_date",currStr);
//        put("result_type",1);
//        put("token",token);
//        put("appid","");
//        put("spid","");
//        put("_",String.valueOf(System.currentTimeMillis()));
//      }
//    };
//    ForestResponse forestResponse = wechatMpApi.queryIncomeData(params,(request, cookies) -> {
//      cookies.addAllCookies(forestCookies);
//    });
//    String resContent = forestResponse.getContent();
//    return JSONObject.parseObject(resContent);
//  }
//
//
//  /**
//   * 根据cookies参数获取账号需要的数据
//   * @param wechatMpAccount
//   * @return
//   */
//  public WechatMpData queryDataInfo(WechatMpAccount wechatMpAccount){
//    WechatMpData wechatMpData = new WechatMpData(); //返回参数
//    WechatMpTokenVo wechatMpTokenVo =  queryToken(wechatMpAccount.getCookies());
//    List<ForestCookie> forestCookies = WxUtil.resetForestCookie(wechatMpAccount.getCookies());
//    //获取token后执行的操作
//    if(wechatMpTokenVo != null && XStringUtils.isNotEmpty(wechatMpTokenVo.getToken())) {
//      //获取账号的基础信息
//      ForestResponse responseInfo = wechatMpApi.queryDataInfo(wechatMpTokenVo.getToken(), (request, cookies) -> {
//        cookies.addAllCookies(forestCookies);
//      });
//      String resIndex = wechatMpApi.toIndex(wechatMpTokenVo.getToken(),(request1, cookies1) -> {
//        cookies1.addAllCookies(forestCookies);
//      });
//      Document doc = Jsoup.parse(resIndex);
//      Elements elements = doc.getElementsByClass("weui-desktop-account__thumb");
//      int num4Idx = resIndex.indexOf("num4"); //获取昨日新增的首个下标
//      String num4Datas = resIndex.substring(num4Idx,num4Idx + 100); //获取最近的100个字符
//      String addFansNum =  num4Datas.substring(num4Datas.indexOf(">") + 1,num4Datas.indexOf("<"));
//      wechatMpData.setAddFans(Integer.parseInt(addFansNum));
//      String headImage = elements.attr("src");
//      if(XStringUtils.isNotEmpty(responseInfo.getContent())){
//        JSONObject jsonObject = JSONObject.parseObject(responseInfo.getContent());
//        if(jsonObject.getJSONObject("base_resp").getInteger("ret") == 0 ){
//          JSONObject settingInfo = jsonObject.getJSONObject("setting_info"); //设置页面内容
//          if(XStringUtils.isNotEmpty(settingInfo.getString("biz_category_info"))){
//            JSONArray bizCategories = settingInfo.getJSONObject("biz_category_info").getJSONArray("biz_categories");
//            String accountClassify = bizCategories.stream().map(i -> ((JSONObject) i).getString("first_cate_name")).collect(Collectors.joining(","));
//            wechatMpData.setAccountClassify(accountClassify);
//          }
//          if(XStringUtils.isNotEmpty(settingInfo.getString("bind_finder_status"))){
//            String  finderNickname = XStringUtils.getNullBlankStr(settingInfo.getJSONObject("bind_finder_status").getString("finder_nickname"));
//            wechatMpData.setFinderNickname(finderNickname);
//          }
//          String nickname = settingInfo.getJSONObject("nickname").getString("nickname");
//          JSONArray changeInfoList = settingInfo.getJSONObject("nickname")
//                  .getJSONObject("nickname_mod_list").getJSONArray("change_info_list");
//          for(int i =0;i< changeInfoList.size();i++){
//            JSONObject itemOb = changeInfoList.getJSONObject(i);
//            String  showWords = itemOb.getString("show_words");
//            if(showWords.equals("注册")){
//              String timeStr = itemOb.getString("time_str");
//              wechatMpData.setRegisterTime(timeStr);
//            }
//          }
//          String originId = settingInfo.getString("original_username");
//          String signature = settingInfo.getJSONObject("intro").getString("signature");
//          String bindEmail = settingInfo.getJSONObject("bind_email").getString("account");
//          String name = settingInfo.getJSONObject("contractor_info").getString("name");
//          int totalFansNum =  settingInfo.getInteger("total_fans_num");
//          //公众号的数据
//          wechatMpData.setOriginId(originId);
//          wechatMpData.setBindEmail(bindEmail);
//          wechatMpData.setIndividualName(name); //注册资质名称
//          wechatMpData.setTotalFansNum(totalFansNum);
//          wechatMpData.setNickname(nickname);
//          wechatMpData.setSignature(signature);
//          wechatMpData.setHeadImage(headImage);
//        }
//      }
//      //获取收款公司名称
//      Long dataTime = System.currentTimeMillis(); //获取当前时间戳
//      ForestResponse resBank = wechatMpApi.queryBankInfoData(wechatMpTokenVo.getToken(),String.valueOf(dataTime), (request, cookies) -> {
//        cookies.addAllCookies(forestCookies);
//      });
//      if(XStringUtils.isNotEmpty(resBank.getContent())){
//        JSONObject bankInfoContent = JSONObject.parseObject(resBank.getContent());
//        if(bankInfoContent.getJSONObject("base_resp").getInteger("ret") == 0){
//          String bankAccountName = bankInfoContent.getJSONObject("publisher_info").getJSONObject("publisher_base_info")
//                  .getJSONObject("bank_info").getString("bank_account_name");
//          int bankAcctStatus = bankInfoContent.getJSONObject("account_info").getInteger("acct_status"); //是否已开通流量主
//          wechatMpData.setBankAccountName(XStringUtils.getNullBlankStr(bankAccountName));
//          if(bankAcctStatus == 1){ //已开通流量主的情况下获取昨日收益数据
//            wechatMpData.setBankAcctStatus(bankAcctStatus);
//            //获取收益数据
//            JSONObject  incomeJson = queryBankInfoData(wechatMpTokenVo.getToken(),wechatMpAccount.getCookies());
//            wechatMpData.setYesterdayIncome(incomeJson.getInteger("yesterday_income")); //获取昨日收入
//            wechatMpData.setTotalIncome(incomeJson.getInteger("total_income")); ; //获取总收入
//            wechatMpData.setLastWeekIncome(incomeJson.getInteger("last_week_income")); //获取最近一周的收益
//            wechatMpData.setLastMonthIncome(incomeJson.getInteger("last_month_income")); //获取最近一个月的收益
//          }
//        }
//      }
//      int readNum = queryReadNum(wechatMpTokenVo.getToken(),wechatMpAccount.getCookies()); //获取昨日阅读量数据
//      wechatMpData.setReadNum(readNum);
//      wechatMpAccount.setLoginStatus(1);
//      wechatMpAccountService.updateById(wechatMpAccount);
//    }else{
//      wechatMpAccount.setLoginStatus(0);
//      wechatMpAccountService.updateById(wechatMpAccount);
//    }
//    return wechatMpData;
//  }
//
//
//  /**
//   * 获取昨日阅读量数据
//   * @return
//   */
//  public int queryReadNum(String token,String cookiesStr){
//    int readNum = 0;
//    Map<String,String> args = new HashMap<String,String>();
//    Date today = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24);
//    String yesterday =   DateUtils.date2Str(today,new SimpleDateFormat("yyyyMMdd")); //获取昨天日期的字符串
//    args.put("begin_date",yesterday);
//    args.put("end_date",yesterday);
//    String scope = JSONObject.toJSONString(args);
//    Map<String,Object> formData = new HashMap<String,Object>(){
//      {
//        put("action","query");
//        put("busi",3);
//        put("tmpl",2);
//        put("args",scope);
//        put("token",token);
//        put("lang","zh_CN");
//        put("f","json");
//        put("ajax",1);
//      }
//    };
//    List<ForestCookie> forestCookies = WxUtil.resetForestCookie(cookiesStr);
//    ForestResponse  forestResponse =  wechatMpApi.queryReadNumData(formData,(request, cookies) ->{
//      cookies.addAllCookies(forestCookies);
//    });
//    if (XStringUtils.isNotEmpty(forestResponse.getContent())){
//      WxResultBody<List<readNumData>> wxResultBody =   WechatUtil.parseWxResultBody(forestResponse.getContent(),
//              new TypeReference<WxResultBody<List<readNumData>>>() {});
//      if(wxResultBody.getBase_resp().getRet() == 0){
//        List<readNumData> dataList =  wxResultBody.getData();
//        for (readNumData readNumData : dataList) {
//          //判断当前的参数是否为昨日阅读数据
//          if(readNumData.getScene().equals("99999999")){ //获取所属分类
//            readNum =  Integer.parseInt(readNumData.getRead_pv());
//          }
//        }
//      }
//    }
//    return readNum;
//  }
//
//
//  /**
//   * 根据图片链接裁剪图片
//   * @return
//   */
//  public List<String> cropImages(String headImageUrl,String token,List<ForestCookie> forestCookies){
//    List<String> images = new ArrayList<>();
//    Map<String,Object> params = new HashMap<>();
//    params.put("imgurl",headImageUrl);
//    params.put("size_count",2);
//    params.put("size0_x1",0);
//    params.put("size0_y1",0.18157181571815717);
//    params.put("size0_x2",1);
//    params.put("size0_y2",0.8204462895692787);
//    params.put("size1_x1",0.16787003610108303);
//    params.put("size1_y1",0);
//    params.put("size1_x2",0.8339350180505415);
//    params.put("size1_y2",1);
//    params.put("token",token);
//    params.put("lang","zh_CN");
//    params.put("f","json");
//    params.put("ajax",1);
//    ForestResponse  forestResponse = wechatMpApi.cropImages(params,(request, cookies) ->{
//      cookies.addAllCookies(forestCookies);
//    });
//    JSONObject joRes = JSONObject.parseObject(XStringUtils.getNullBlankStr(forestResponse.getContent()));
//    if(joRes.getJSONObject("base_resp").getInteger("ret") == 0){
//      String image235 = XStringUtils.getNullBlankStr(joRes.getJSONArray("result").getJSONObject(0).getString("cdnurl"));
//      String image1 = XStringUtils.getNullBlankStr(joRes.getJSONArray("result").getJSONObject(1).getString("cdnurl"));
//      images.add(image235);
//      images.add(image1);
//    }
//    return images;
//  }
//
//
//  /**
//   * 调用智能广告列表
//   * @return
//   */
//  public String getAdSetting(String token,List<ForestCookie> forestCookies){
//    return wechatMpApi.getAdSetting(token,Math.random(),(request, cookies) ->{
//      cookies.addAllCookies(forestCookies);
//    });
//  }
//
//
//  /**
//   * 公众号将文章保存到草稿箱并返回appmsgid
//   * @return
//   */
//  public String saveDraughtArticle(List<Map<String,Object>> articles,String cookiesStr){
//    String appMsgId = "";
//    try{
//      WechatMpTokenVo wechatMpTokenVo =  queryToken(cookiesStr);
//      List<ForestCookie> forestCookies = WxUtil.resetForestCookie(cookiesStr);
//      if(XStringUtils.isNotEmpty(wechatMpTokenVo.getToken())){
//        String categoriesList = "";
//        String adStr = getAdSetting(wechatMpTokenVo.getToken(),forestCookies);
//        if(XStringUtils.isNotEmpty(adStr)){
//          JSONObject adJsonData = JSONObject.parseObject(adStr);
//          categoriesList =  adJsonData.getJSONObject("advert_setting").getJSONArray("categories_list").toJSONString();
//        }
//        Map<String,Object> body = new HashMap<String,Object>(){
//          {
//            put("token",wechatMpTokenVo.getToken());
//            put("lang","zh_CN");
//            put("f","json");
//            put("ajax",1);
//            put("random",Math.random());
//            put("AppMsgId","");
//            put("count",articles.size());
//            put("data_seq","");
//            put("operate_from","Chrome");
//            put("isnew",0);
//            put("articlenum",articles.size());
//            put("remind_flag",null);
//          }
//        };
//        for(int i = 0; i < articles.size();i++){
//          List<String> cdnImageCover = cropImages(XStringUtils.getNullBlankStr(articles.get(i).get("headImage")),wechatMpTokenVo.getToken(),forestCookies);
//          body.put("is_finder_video" + i,0);
//          body.put("finder_draft_id" + i,0);
//          body.put("applyori" + i,0);
//          body.put("ad_video_transition" + i,"");
//          body.put("can_reward" + i,0);
//          body.put("pay_gifts_count" + i,0);
//          body.put("reward_reply_id" + i,"");
//          body.put("related_video" + i,"");
//          body.put("is_video_recommend" + i,-1);
//          body.put("title" + i,XStringUtils.getNullBlankStr(articles.get(i).get("title")));
//          body.put("author" + i,XStringUtils.getNullBlankStr(articles.get(i).get("author")));
//          body.put("writerid" + i,0);
//          body.put("fileid" + i,"");
//          body.put("digest" + i,XStringUtils.getNullBlankStr(articles.get(i).get("digest")));
//          body.put("auto_gen_digest" + i,1);
//          body.put("content" + i,XStringUtils.getNullBlankStr(articles.get(i).get("content")));
//          body.put("sourceurl" + i,"");
//          body.put("last_choose_cover_from" + i,0);
//          body.put("need_open_comment" + i,0);
//          body.put("only_fans_can_comment" + i,0);
//          body.put("only_fans_days_can_comment" + i,0);
//          body.put("reply_flag" + i,0);
//          body.put("cdn_url" + i,cdnImageCover != null && cdnImageCover.size() > 0  ? cdnImageCover.get(0) : "");//2.35：1
//          body.put("cdn_235_1_url" + i,cdnImageCover != null && cdnImageCover.size() > 0 ? cdnImageCover.get(0) : "");//2.35：1
//          body.put("cdn_16_9_url" + i,cdnImageCover != null && cdnImageCover.size() > 0 ? cdnImageCover.get(0) : ""); //2.35：1
//          body.put("cdn_1_1_url" + i,cdnImageCover != null && cdnImageCover.size() > 0 ? cdnImageCover.get(1) : ""); //1:1
//          body.put("cdn_url_back" + i,XStringUtils.getNullBlankStr(articles.get(i).get("headImage"))); //原始图片
//          body.put("crop_list" + i,JSONObject.parse("{\"crop_list\":[{\"ratio\":\"2.35_1\",\"x1\":0,\"y1\":67,\"x2\":554,\"y2\":302},{\"ratio\":\"1_1\",\"x1\":93,\"y1\":0,\"x2\":462,\"y2\":369}]}"));
//          body.put("music_id" + i,"");
//          body.put("video_id" + i,"");
//          body.put("voteid" + i,XStringUtils.getNullBlankStr(articles.get(i).get("video_id")));
//          body.put("voteismlt" + i,"");
//          body.put("supervoteid" + i,"");
//          body.put("cardid" + i,"");
//          body.put("cardquantity" + i,"");
//          body.put("cardlimit" + i,"");
//          body.put("vid_type" + i,"");
//          body.put("show_cover_pic" + i,0);
//          body.put("shortvideofileid" + i,"");
//          body.put("copyright_type" + i,0);
//          body.put("is_cartoon_copyright" + i,0);
//          body.put("copyright_img_list" + i,JSONObject.parse("{\"max_width\":578,\"img_list\":[]}"));
//          body.put("releasefirst" + i,"");
//          body.put("platform" + i,"");
//          body.put("reprint_permit_type" + i,"");
//          body.put("allow_reprint" + i,"");
//          body.put("allow_reprint_modify" + i,"");
//          body.put("original_article_type" + i,"");
//          body.put("ori_white_list" + i,"");
//          body.put("video_ori_status" + i,XStringUtils.getNullBlankStr(articles.get(i).get("videoOriStatus")));
//          body.put("hit_nickname" + i,"");
//          body.put("free_content" + i,"");
//          body.put("fee" + i,0);
//          body.put("ad_id" + i,"");
//          body.put("guide_words" + i,"");
//          body.put("is_share_copyright" + i,0);
//          body.put("share_copyright_url" + i,"");
//          body.put("source_article_type" + i,"");
//          body.put("reprint_recommend_title" + i,"");
//          body.put("reprint_recommend_content" + i,"");
//          body.put("share_page_type" + i,XStringUtils.getNullBlankStr(articles.get(i).get("sharePageType")).equals("5") ? 5 : 0);
//          body.put("share_imageinfo" + i,JSONObject.parse("{\"list\":[]}"));
//          body.put("share_video_id" + i,XStringUtils.getNullBlankStr(articles.get(i).get("share_video_id")));
//          body.put("dot" + i,JSONObject.parse("{}"));
//          body.put("share_voice_id" + i,"");
//          body.put("insert_ad_mode" + i,2);
//          body.put("categories_list" + i,categoriesList);
//          body.put("compose_info" + i,JSONObject.parse("{list:[{blockIdx:1,imgList:null,text:\"\"}]}"));
//          body.put("is_pay_subscribe" + i,0);
//          body.put("pay_fee" + i,"");
//          body.put("pay_preview_percent" + i,"");
//          body.put("pay_desc" + i,"");
//          body.put("appmsg_album_info" + i,XStringUtils.getNullBlankStr(articles.get(i).get("appmsgAlbumInfo"))); //话题内容
//          body.put("can_insert_ad" + i,1);
//          body.put("audio_info" + i,JSONObject.parse("{\"audio_infos\":[]}"));
//          body.put("danmu_pub_type" + i + "_0",XStringUtils.getNullBlankStr(articles.get(i).get("danmu_pub_type")).equals("1") ? 1 : 0);
//          body.put("is_set_sync_to_finder" + i,0);
//          body.put("sync_to_finder_cover" + i,"");
//          body.put("sync_to_finder_cover_source" + i,"");
//        }
//        String  res =  wechatMpApi.saveDraught(body,wechatMpTokenVo.getToken(),77,(request, cookies) ->{
//          cookies.addAllCookies(forestCookies);
//        });
//        JSONObject jo = JSONObject.parseObject(XStringUtils.getNullBlankStr(res));
//        if(jo.getJSONObject("base_resp").getInteger("ret") == 0){
//          appMsgId = XStringUtils.getNullBlankStr(jo.getString("appMsgId"));
//          log.info(jo.toJSONString());
//        }
//      }
//    }catch (Exception e){
//      e.printStackTrace();
//    }
//    return appMsgId;
//  }
//
//
//  /**
//   * 保存视频到素材库
//   * @param wechatMpVideoVo
//   * @return
//   */
//  public String saveDraughtVideo(WechatMpVideoVo wechatMpVideoVo){
//    String fileName =  wechatMpVideoVo.getFilename();
//    if(XStringUtils.isNotEmpty(fileName) && fileName.contains(".mp4")){
//      wechatMpVideoVo.setFilename( fileName.substring(0,fileName.indexOf(".mp4")));
//    }
//    List<String> cdnImageCover = cropImages(XStringUtils.getNullBlankStr(wechatMpVideoVo.getCdnUrl()),wechatMpVideoVo.getToken(),wechatMpVideoVo.getForestCookies());
//    Map<String,Object> params = new HashMap<String,Object>(){
//      {
//        put("title0",wechatMpVideoVo.getFilename());
//        put("digest0","");
//        put("video_desc0","");
//        put("newsubcat",wechatMpVideoVo.getNewsubcat());
//        put("newcat",wechatMpVideoVo.getNewcat());
//        put("tags","");
//        put("type",15);
//        put("is_open_danmu",1);
//        put("is_only_fans_can_pub",0);
//        put("is_only_fans_days_can_pub",0);
//        put("AppMsgId","");
//        put("need_open_comment0",1);
//        put("only_fans_can_comment0",0);
//        put("reply_flag0",0);
//        put("content0",wechatMpVideoVo.getVid());
//        put("contenturl0","");
//        put("count",1);
//        put("fileid0","");
//        put("cdn_url0",wechatMpVideoVo.getCdnUrl());
//        put("author0","");
//        put("video_duration",wechatMpVideoVo.getFileSize());
//        put("appmsg_album_review",1);
//        put("only_fans_days_can_comment0",0);
//        put("declare_ori",0);
//        put("can_reward0",0);
//        put("sync_txvideo",1);
//        put("tags_type","");
//        put("cdn_16_9_url0",cdnImageCover != null && cdnImageCover.size() > 0  ? cdnImageCover.get(0) : "");
//        put("cdn_1_1_url0", cdnImageCover != null && cdnImageCover.size() > 0  ? cdnImageCover.get(0) : "");
//        put("cover_to_crop_url",wechatMpVideoVo.getCover_to_crop_url());
//        put("crop_coordinate",JSON.toJSONString("[{\"x\":0,\"y\":6,\"x2\":544,\"y2\":312,\"w\":544,\"h\":306},{\"x\":0,\"y\":0,\"x2\":312,\"y2\":312,\"w\":312,\"h\":312},{\"x\":0,\"y\":6,\"x2\":544,\"y2\":312,\"w\":544,\"h\":306}]"));
//        put("text_coordinate",null);
//        put("is_mp_video",1);
//        put("needCheckOriVideoPrompt",1);
//        put("cover_idx0",1);
//        put("cover_type0",2);
//        put("token",wechatMpVideoVo.getToken());
//        put("lang","zh_CN");
//        put("f","json");
//        put("ajax",1);
//      }
//    };
//    return  wechatMpApi.saveDraught(params,wechatMpVideoVo.getToken(),15,(request, cookies) ->{
//      cookies.addAllCookies(wechatMpVideoVo.getForestCookies());
//    });
//  }
//
//
//
//
////    =====================================检查文章参数===================================
//
//
//  /**
//   * 检查文章音乐
//   * @param forestCookies
//   * @param appMsgId
//   * @param token
//   * @return
//   */
//  public String checkMusic(List<ForestCookie> forestCookies,String  appMsgId,String token){
//    Map<String,Object> body = new HashMap<String,Object>(){
//      {
//        put("appmsgid",appMsgId);
//        put("masssend_check",1);
//        put("token",token);
//        put("lang","zh_CN");
//        put("f","json");
//        put("ajax",1);
//      }
//    };
//    return wechatMpApi.checkMusic(body,appMsgId,token,(forestRequest, cookie) ->{cookie.addAllCookies(forestCookies);});
//  }
//
//
//  /**
//   * 检查广告
//   * @param forestCookies
//   * @param appMsgId
//   * @param token
//   * @return
//   */
//  public String checkAd(List<ForestCookie> forestCookies,String  appMsgId,String token){
//    Map<String,Object> body = new HashMap<String,Object>(){
//      {
//        put("token",token);
//        put("lang","zh_CN");
//        put("f","json");
//        put("ajax",1);
//        put("random",Math.random());
//        put("appmsg_id",appMsgId);
//      }
//    };
//    return  wechatMpApi.checkAd(body,appMsgId,token,(forestRequest, cookie) ->{cookie.addAllCookies(forestCookies);});
//  }
//
//  /**
//   * 检查账号密码
//   * @param forestCookies
//   * @param appMsgId
//   * @param token
//   * @return
//   */
//  public String checkSameMaterial(List<ForestCookie> forestCookies,String  appMsgId,String token){
//    Map<String,Object> body = new HashMap<String,Object>(){
//      {
//        put("msgid",appMsgId);
//        put("token",token);
//        put("lang","zh_CN");
//        put("f","json");
//        put("ajax",1);
//      }
//    };
//    return  wechatMpApi.checkSameMaterial(body,appMsgId,token,(forestRequest, cookie) ->{cookie.addAllCookies(forestCookies);});
//  }
//
//
//
//
//  /**
//   * 检查文章原创度
//   * @return
//   */
//  public String getAppMsgCopyright(String token,List<ForestCookie> forestCookies,String appMsgid,int checkNum){
//    Map<String,Object> body = new HashMap<String,Object>(){
//      {
//        put("token",token);
//        put("lang","zh_CN");
//        put("f","json");
//        put("ajax",1);
//        put("random",Math.random());
//        put("first_check",checkNum);
//        put("type",10);
//        put("appmsgid",appMsgid);
//      }
//    };
//    return wechatMpApi.getAppMsgCopyright(body,appMsgid,token,(forestRequest, cookies) -> {cookies.addAllCookies(forestCookies);});
//  }
//
//
//  /**
//   * 发送文章前对参数的封装
//   * @return
//   */
//  public String massSendArticle(String sendTime,String appMsgId,List<ForestCookie> forestCookies,String token){
//    Map<String,Object> body = new HashMap<String,Object>(){
//      {
//        put("token",token);
//        put("lang","zh_CN");
//        put("f","json");
//        put("ajax",1);
//        put("random",Math.random());
//        put("ack","");
//        put("code","");
//        put("reprint_info","");
//        put("reprint_confirm",0);
//        put("list","");
//        put("groupid","");
//        put("sex",0);
//        put("country","");
//        put("province","");
//        put("city","");
//        put("send_time",sendTime);
//        put("type",10);
//        put("share_page",1);
//        put("synctxweibo",0);
//        put("operation_seq",(Calendar.getInstance().getTimeInMillis()/1000) + "_" + WxUtils.getRado16());
//        put("req_id",WxUtils.getRado32());
//        put("req_time",Calendar.getInstance().getTimeInMillis());
//        put("sync_version",1);
//        put("isFreePublish",0);
//        put("appmsgid",appMsgId);
//        put("isMulti",1);
//        put("direct_send",1);
//      }
//    };
//    String massSendArticle = wechatMpApi.massSendArticle(body,appMsgId,token,Math.random(),(request, cookies) ->{cookies.addAllCookies(forestCookies);});
//    log.info(massSendArticle);
//    return wechatMpApi.sendArticles(body,token,appMsgId,(request, cookies) ->{cookies.addAllCookies(forestCookies);});
//  }
//
//  /**
//   * 定时 发送文章 & 视频
//   * @return
//   */
//  public String sendArticle(String cookiesStr,String appMsgId,String sendTime){
//    String res = "";
//    List<ForestCookie> forestCookies = WxUtil.resetForestCookie(cookiesStr); //获取格式后的cookies参数信息
//    WechatMpTokenVo wechatMpTokenVo =  queryToken(cookiesStr); //获取token
//    if(XStringUtils.isNotEmpty(wechatMpTokenVo.getToken())){
//      checkMusic(forestCookies,appMsgId,wechatMpTokenVo.getToken()); //检查音乐
//      checkAd(forestCookies,appMsgId,wechatMpTokenVo.getToken());  //检查广告
//      getAppMsgCopyright(wechatMpTokenVo.getToken(),forestCookies,appMsgId,1); //检查原创度
//      checkSameMaterial(forestCookies,appMsgId,wechatMpTokenVo.getToken()); //检查账号密码
//      res =  massSendArticle(sendTime,appMsgId,forestCookies,wechatMpTokenVo.getToken());
//    }
//    return res;
//  }
//
//
//  /**
//   * 开通流量主
//   * @return
//   */
//  public String dredgeFlowMain(WechatMpAccount wechatMpAccount){
//    Long time =  Calendar.getInstance().getTimeInMillis()/1000; //当前时间戳
//    WechatMpTokenVo wechatMpTokenVo =  queryToken(wechatMpAccount.getCookies()); //获取token
//    List<ForestCookie> forestCookies = WxUtil.resetForestCookie(wechatMpAccount.getCookies());
//    Map<String,Object> params = new HashMap<String,Object>(){
//      {
//        put("action","create_account");
//        put("monetize_methods","[1,1,1,4,1]");
//        put("biz_ads_slot","[1,3,7,16]");
//        put("token",wechatMpTokenVo.getToken());
//        put("appid","");
//        put("spid","");
//        put("_",time);
//      }
//    };
//    String res =   wechatMpApi.publisherMgr(wechatMpTokenVo.getToken(),params,(request, cookies) ->{cookies.addAllCookies(forestCookies);});
//    String resUUID =  wechatMpApi.createUuid(wechatMpTokenVo.getToken(),time.toString(),(request, cookies) ->{cookies.addAllCookies(forestCookies);});
//    if(XStringUtils.isNotEmpty(resUUID)){
//      JSONObject jsonObject =  JSONObject.parseObject(resUUID);
//      String uuid = jsonObject.getJSONObject("data").getString("uuid");
//      if(XStringUtils.isNotEmpty(uuid)){
//        wechatMpApi.queryUuid(uuid,time.toString(),wechatMpTokenVo.getToken(),(request, cookies) ->{cookies.addAllCookies(forestCookies);});
//      }
//    }
//    return res;
//  }
//
//
//  /**
//   * 初始化视频数据
//   * @return
//   */
//  public String initUpload(WechatMpVideoVo wechatMpVideoVo){
//    Map<String,Object> params = new HashMap<>();
//    params.put("max_part_size",4194304);
//    params.put("filename",wechatMpVideoVo.getFilename());
//    params.put("filesize",wechatMpVideoVo.getFileSize());
//    params.put("token",wechatMpVideoVo.getToken());
//    params.put("lang","zh_CN");
//    params.put("f","json");
//    params.put("ajax",1);
//    return  wechatMpApi.initUpload(params,wechatMpVideoVo.getToken(),(request, cookies) ->{
//      cookies.addAllCookies(wechatMpVideoVo.getForestCookies());
//    });
//  }
//
//  /**
//   * 账号上传视频
//   * @param wechatMpVideoVo
//   * @return
//   */
//  public String uploadVideo(WechatMpVideoVo wechatMpVideoVo, byte[] bytes, int partNum)
//          throws IOException, InterruptedException {
//    String videoRes =  wechatMpApi.uploadVideo(wechatMpVideoVo.getFileSize(),
//            wechatMpVideoVo.getVid(),wechatMpVideoVo.getToken(),partNum,
//            wechatMpVideoVo.getRandom(),bytes,(request, cookies) -> {
//              cookies.addAllCookies(wechatMpVideoVo.getForestCookies());
//            });
//    return videoRes;
//  }
//
//  /**
//   * 视频完成上传
//   * @return
//   */
//  public String uploadFinish(WechatMpVideoVo wechatMpVideoVo){
//    return  wechatMpApi.uploadFinish(wechatMpVideoVo.getVid(),wechatMpVideoVo.getToken(),wechatMpVideoVo.getRandom(),(request, cookies) -> {
//      cookies.addAllCookies(wechatMpVideoVo.getForestCookies());
//    });
//  }
//
//  /**
//   * 获取 ticket
//   * @return
//   */
//  public String getTicket(WechatMpVideoVo wechatMpVideoVo){
//    String ticket = "";
//    String res =   wechatMpApi.getTicket(wechatMpVideoVo.getToken(),(request, cookies) -> {
//      cookies.addAllCookies(wechatMpVideoVo.getForestCookies());
//    });
//    if(XStringUtils.isNotEmpty(res)){
//      Document  doc = Jsoup.parse(res);
//      Elements el = doc.getElementsByClass("weui-desktop-dropdown__list-ele");
//      for(Element e : el){
//        Elements elements = e.select("weui-desktop-dropdown__list__section__list");
//        System.out.println(elements);
//      }
//      int startIndex  = res.indexOf("ticket");
//      String resData =  res.substring(startIndex,startIndex + 70); //截取代码片段
//      if(XStringUtils.isNotEmpty(resData)){
//        ticket = resData.substring(resData.indexOf("\"") + 1,resData.indexOf("\","));
//      }
//    }
//    return ticket;
//  }
//
//
//  /**
//   * 根据视频字节流获取视频封面
//   * @return
//   */
//  public String uploadCdn(File file,WechatMpVideoVo wechatMpVideoVo,String ticket){
//    String res =  wechatMpApi.uploadCdn(file,wechatMpVideoVo.getOriginId(),wechatMpVideoVo.getFileSize(),
//            ticket,wechatMpVideoVo.getToken(),wechatMpVideoVo.getTime(),(request, cookies) -> {
//              cookies.addAllCookies(wechatMpVideoVo.getForestCookies());});
//    if(XStringUtils.isNotEmpty(res)){
//      JSONObject jsonObject = JSONObject.parseObject(res);
//      if(jsonObject.getJSONObject("base_resp").getInteger("ret") == 0){
//        return jsonObject.getString("content");
//      }
//    }
//    return null;
//  }
//
//
//  /**
//   * 获取当天发布的视频id wxv_id
//   * @return
//   */
//  public List<WechatMpVideoData> getSendVideoIds(WechatMpVideoVo wechatMpVideoVo, List<WechatMpPublishList> wechatMpPublishLists){
//    String res = wechatMpApi.getSendVideoIds(8, wechatMpVideoVo.getToken(),(forestRequest, forestCookies) -> {
//      forestCookies.addAllCookies(wechatMpVideoVo.getForestCookies());
//    });
//    List<WechatMpVideoData> videoDataList = new ArrayList<>();
//    if(XStringUtils.isNotEmpty(res)){
//      JSONObject jsonObject = JSONObject.parseObject(res);
//      if(jsonObject.getJSONObject("base_resp").getInteger("ret") == 0){
//        JSONArray jsonArray =  jsonObject.getJSONObject("app_msg_info").getJSONArray("item");
//        for(WechatMpPublishList item :wechatMpPublishLists){
//          for( int i = 0;i<jsonArray.size();i++){
//            JSONObject resData =  jsonArray.getJSONObject(i);
//            WechatMpVideoData wechatMpVideoData =   JSONObject.toJavaObject(resData,WechatMpVideoData.class);
//            if(item.getAid().equals(wechatMpVideoData.getApp_id())){
//              videoDataList.add(wechatMpVideoData);
//            }
//          }
//        }
//
//      }
//    }
//    return videoDataList;
//  }
//
//
//  /**
//   * 保存国家和地区
//   * @param token
//   * @return
//   */
//  public String savecountry(String token,String cookiesStr){
//    List<ForestCookie> forestCookies = WxUtil.resetForestCookie(cookiesStr); //获取格式后的cookies参数信息
//    Map<String,Object> params = new HashMap<>();
//    params.put("token",token);
//    params.put("lang","zh_CN");
//    params.put("f","json");
//    params.put("ajax",1);
//    params.put("random",Math.random());
//    params.put("country",1017);
//    return wechatMpApi.savecountry(params,((request, cookies) -> {
//      cookies.addAllCookies(forestCookies);
//    }));
//  }
//
//
//  /**
//   *  选中订阅号或服务号类型
//   * @return
//   */
//  public String registerpage(String token,String cookiesStr){
//    List<ForestCookie> forestCookies = WxUtil.resetForestCookie(cookiesStr); //获取格式后的cookies参数信息
//    Map<String,Object> params = new HashMap<String,Object>(){
//      {
//        put("token",token);
//        put("lang","zh_CN");
//        put("f","json");
//        put("ajax",1);
//        put("random",Math.random());
//        put("action","savetype");
//        put("type",1); // 1、订阅号  2、服务号
//      }
//    };
//    return wechatMpApi.registerpage(params,((request, cookies) -> {
//      cookies.addAllCookies(forestCookies);
//    }));
//  }
//
//
//  /**
//   * 分段保存企业名称
//   * @param name
//   * @return
//   */
//  public String contractorsubmit(String name,String token,List<ForestCookie> forestCookie){
//    Map<String,Object> params = new HashMap<>();
//    params.put("token",token);
//    params.put("lang","zh_CN");
//    params.put("f","json");
//    params.put("ajax",1);
//    params.put("random",Math.random());
//    params.put("action","check_principal_name");
//    params.put("contractor_action","enterprise_contractor_set");
//    params.put("is_individual",0);
//    params.put("name",name);
//    return wechatMpApi.contractorsubmit(params,((forestRequest, forestCookies) -> {
//      forestCookies.addAllCookies(forestCookie);
//    }));
//  }
//
//
//  /**
//   * 获取法人验证码的getticket
//   * @param token
//   * @param wechatMpCreateAccount
//   * @return
//   */
//  public String mastersafeqrcode(String token, WechatMpCreateAccount wechatMpCreateAccount,List<ForestCookie> forestCookie){
//    Map<String,Object> params = new HashMap<>();
//    params.put("token",token);
//    params.put("lang","zh_CN");
//    params.put("f","json");
//    params.put("ajax",1);
//    params.put("random",Math.random());
//    params.put("action","getticket");
//    params.put("size",120);
//    params.put("scene",0);
//    params.put("typeid",26);
//    params.put("data","{\"operator_name\":\""+wechatMpCreateAccount.getLegalPersonName()+"\",\"operator_id\":\""+wechatMpCreateAccount.getIdentityPersonCard()+"\"}");
//    params.put("extra","{\"operator_name\":\""+wechatMpCreateAccount.getLegalPersonName()+"\",\"operator_id\":\""+wechatMpCreateAccount.getIdentityPersonCard()+"\",\"subject\":\""+wechatMpCreateAccount.getEnterpriseName()+"\",\"refill\":0,\"service_type\":1,\"is_from_legal_person\":1}");
//    params.put("operator_name",wechatMpCreateAccount.getLegalPersonName());
//    params.put("operator_id",wechatMpCreateAccount.getIdentityPersonCard());
//    String resGetticket = wechatMpApi.mastersafeqrcode(params,((forestRequest, forestCookies) -> {
//      forestCookies.addAllCookies(forestCookie);
//    }));
//    if(JSONObject.parseObject(resGetticket).getJSONObject("base_resp").getInteger("ret") == 0){
//      String ticket =  JSONObject.parseObject(resGetticket).getString("qrcheck_ticket");
//      if(XStringUtils.isNotEmpty(ticket)){
//        ForestResponse imageResponse = wechatMpApi.mastersafeqrcodeGetqrcode(ticket,Math.random(),token,((forestRequest, forestCookies) -> {
//          forestCookies.addAllCookies(forestCookie);
//        }));
////               String res = imageResponse.getResult();
////               System.out.println(image);
//      }
////            CommonUtils.upload()
//    }
//
//    return "";
//  }
//
//
//  /**
//   * 获取账号粉丝迁移二维码获取的参数
//   * @param token
//   * @param forestCookie
//   * @return
//   */
//  public String getticket(String token,List<ForestCookie> forestCookie){
//    Map<String,Object> params = new HashMap<>();
//    params.put("token",token);
//    params.put("lang","zh_CN");
//    params.put("f","json");
//    params.put("ajax",1);
//    params.put("typeid",140);
//    params.put("action","getticket");
//    return wechatMpApi.getticket(params,token,((forestRequest, forestCookies) -> {
//      forestCookies.addAllCookies(forestCookie);
//    }));
//  }
//
//
//  /**
//   * 粉丝迁移提交参数信息
//   * @param token
//   * @param forestCookie
//   * @return
//   */
//  public String biztransfer(String token,List<ForestCookie> forestCookie){
//    Map<String,Object> params = new HashMap<>();
//    params.put("agree",1);
//    params.put("step","agree_proto");
//    params.put("token",token);
//    params.put("lang","zh_CN");
//    params.put("f","json");
//    params.put("ajax",1);
//    return wechatMpApi.biztransfer(params,token,(((forestRequest, cookies) -> {
//      cookies.addAllCookies(forestCookie);
//    })));
//  }

  }


